package com.bj.disc.service

import android.app.Activity
import android.app.IntentService
import android.content.Intent
import com.ai3d.rfid.common.log.Logcat
import com.ai3d.rfid.common.proxy.MMKVProxy
import com.ai3d.rfid.network.download.IDownloadListener
import com.ai3d.rfid.network.proxy.NetworkProxy
import com.bj.disc.util.DiscConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Call
import java.io.File

/**
 * @ProjectName : disc
 * @Author : weijinsong
 * @Time : 2023/7/15 10:38
 * @Description : 文件描述
 */
class MyIntentService : IntentService("MyIntentService") {
    private val TAG = "MyIntentService"

    companion object {
        fun startMyIntentService(activity: Activity) {
            val intent = Intent(activity, MyIntentService::class.java)
            activity.startService(intent)
        }
    }

    override fun onHandleIntent(intent: Intent?) {
        downloadStaticFile()
        // 打印当前线程的id
        Logcat.d(TAG, "Thread id is ${Thread.currentThread().name}")
    }

    override fun onDestroy() {
        super.onDestroy()
        Logcat.d(TAG, "onDestroy executed")
    }

    private fun downloadStaticFile() {
        var call: Call<ResponseBody>? = null
        GlobalScope.launch(Dispatchers.IO) {
            runCatching {
                var range = "bytes=0-"

                // 调用 Retrofit 接口方法下载文件
                var call = NetworkProxy.createDownFileRetrofit(object : IDownloadListener {
                    override fun onStartDownload(length: Long) {
                    }

                    override fun onProgress(progress: Double) {
                    }

                    override fun onComplete(length: Long) {
                    }

                    override fun onFail(errorInfo: String?) {
                    }
                })
                    .downloadFile(DiscConstants.RESOURCE_ZIP_URL, range)
                // 获取 ResponseBody 并进行文件写入
                val response: ResponseBody? = call.execute().body()
                response
            }.onSuccess {
                var isSameFile =
                    it?.contentLength() == null || MMKVProxy.getLong(MMKVProxy.KEY_STATIC_ZIP_FILE_LENGTH) == it?.contentLength()//内容为空代表定点传送已完成
                Logcat.d(
                    TAG,
                    "downloadStaticFile 下次进来是否需要更新资源文件 : ${!isSameFile} ${
                        MMKVProxy.getLong(MMKVProxy.KEY_STATIC_ZIP_FILE_LENGTH)
                    }"
                )
                if (!isSameFile) {//不是同一文件下载进来就下载
                    MMKVProxy.setBoolean(MMKVProxy.KEY_NEED_DOWNLOAD, true)
                    var zipFile = File(DiscConstants.DOWNLOAD_FILE_STATIC_DIR, DiscConstants.DOWNLOAD_FILE_STATIC_FILE_NAME_ZIP)
                    if(zipFile.exists()){
                        zipFile.delete()
                    }
                }
                it?.close()
                call?.cancel()
                stopSelf()
            }.onFailure {
                stopSelf()
            }
        }

    }
}